import { Component, OnInit, ChangeDetectorRef, ViewChild, Inject, forwardRef } from '@angular/core';
import { AppComponent } from '../../../app.component';
import { path } from '../../../path.config';
import { masterService } from '../../../../lib/master.service';
import { NzModalService } from 'ng-zorro-antd';
import { FileUploader } from '../../../../lib/ng2-file-upload';

@Component({
    selector: 'app-goods-invoice-category-management',
    templateUrl: './goods-invoice-category-management.component.html',
    styleUrls: ['./goods-invoice-category-management.component.css']
})
export class GoodsInvoiceCategoryManagementComponent implements OnInit {
    // 列表API
    public getList: any = path.invoiceManage.goodsInvoiceCategory.getGoodsInvoiceList;
    // 开票分类列表查询
    private searchList = path.invoiceManage.invoiceCateManage.getAllInvoiceCate;
    // 修改
    private update = path.invoiceManage.goodsInvoiceCategory.updateRelevance;
    // 上传文件
    private addFileItem = path.imagesUpload.apiUrl;
    // 批量上传
    private batchAddItem = path.invoiceManage.goodsInvoiceCategory.uploadGoodsInvoiceList;

    public rows: Array<any> = [];
    // 获取开票列表
    invoiceSearchList = [];
    invoiceSearchListEdit = [];
    categoryName = '';
    selectCategoryName = '';
    selectCategoryId = 0;
    goodsName = '';
    hasCategory = 2;
    IsActivity = false;
    private btnEnabled: any = 1;
    private selectedGoodsSn = '';
    public IsShow = false;
    // 当前页码
    public page: any = 1;
    // 一共多少页
    public itemsPerPage: number = 10;
    // 分页最多显示的页数
    public maxSize: number = 5;
    // 总页数计数变化时，事件数等于总页数计数
    public numPages: number = 1;
    // 总共的列表项数
    public totalItems: number = 0;
    // 分页器的文本配置
    public localText = {
        firstBtn: '首页',
        lastBtn: '末页',
        previousBtn: '上一页',
        nextBtn: '下一页'
    }

    public filter: any = {
        pageSize: '10',
        pageIndex: '1',
        goodsName: '',
        categoryName: '',
        hasCategory: 2
    }
    constructor(public _masterService: masterService,
        public cdRef: ChangeDetectorRef,
        private confirmServ: NzModalService,
        @Inject(forwardRef(() => AppComponent)) private app: AppComponent) { }

    public ngOnInit() {
        // init的时候获取分类的列表
        this._masterService
            .getData(this.searchList)
            .subscribe((res) => {
                if (res.statusCode == 200) {
                    this.invoiceSearchList = res.data;
                } else if (res.statusCode == 401) {
                    this.app.logOff();
                } else {
                    this.app.toastError('错误信息：' + res.errorMessage);
                }
            });

        this.onChangeTable();
    }

    // 渲染表格
    public onChangeTable = (urlObj?) => {
        if (urlObj) {
            this.filter.pageSize = urlObj.itemsPerPage;
            this.filter.pageIndex = urlObj.page;
        }
        this._masterService
            .getData(this.getList, this.filter)
            .subscribe((res) => {
                if (res.statusCode == 200) {
                    this.rows = res.data.items;
                    this.rows.forEach((row, i) => {
                        if (row.updatedTime) {
                            row.updatedTime = row.updatedTime * 1000;
                        }
                    })
                    this.totalItems = res.data.pagination.totalCount;
                    this.itemsPerPage = res.data.pagination.pageSize;
                    this.page = parseInt(res.data.pagination.pageIndex);
                    this.cdRef.detectChanges();
                } else if (res.statusCode == 401) {
                    this.app.logOff();
                } else {
                    this.app.toastError('错误信息： ' + res.errorMessage);
                }
            })
    }

    // 搜索的时候获取所有开票分类
    getListFunc(categoryName) {
        let urlObject = {
            name: categoryName
        }
        this.IsActivity = true;
        this._masterService
            .getData(this.searchList, urlObject)
            .subscribe((res) => {
                if (res.statusCode == 200) {
                    this.invoiceSearchList = res.data;
                    this.cdRef.detectChanges();
                } else if (res.statusCode == 401) {
                    this.app.logOff();
                } else {
                    this.app.toastError('错误信息：' + res.errorMessage);
                }
            })
    }
    // 搜索列表中已经选中的商品
    addListFunc(name) {
        this.categoryName = name;
        this.getListFunc(name);
    }
    searchFn() {
        this.filter.goodsName = this.goodsName;
        this.filter.categoryName = this.categoryName;
        this.filter.hasCategory = this.hasCategory;
        this.onChangeTable();
    }

    // 以下为编辑代码
    // 显示新建开票模态框
    showUpdateModel(goodsSn) {
        if (goodsSn) {
            this.selectedGoodsSn = goodsSn;
        }
        // init的时候获取分类的列表
        this._masterService
        .getData(this.searchList)
        .subscribe((res) => {
            if (res.statusCode == 200) {
                this.invoiceSearchListEdit = res.data;
            } else if (res.statusCode == 401) {
                this.app.logOff();
            } else {
                this.app.toastError('错误信息：' + res.errorMessage);
            }
        });
        $('#editGoodsInvoiceBox').removeClass('modalBoxHide');
        $('#editGoodsInvoiceContainer').removeClass('modalBoxHide');
    }
    // 设置开票分类
    updateGoodsInvoiceCate() {
        if (!this.selectCategoryId) {
            this.app.toastWarning('请选择开票分类！');
            return;
        }
        // 判断是否选中，选中放入数组中
        let selectedArray = [];
        if (!this.selectedGoodsSn) {
            for (let i = 0; i < this.rows.length; i++) {
                if (this.rows[i].isChecked == true) {
                    selectedArray.push(this.rows[i].sn);
                }
            }
        }
        else {
            selectedArray.push(this.selectedGoodsSn);
        }

        if (selectedArray.length == 0) {
            this.app.toastWarning('所选商品为空！');
            return;
        }
        this.confirmServ.confirm({
            nzTitle: '确定修改？',
            nzOnOk() {
                postSetSelectedGoods(selectedArray);
            }
        })
        let postSetSelectedGoods = (selectedArray) => {
            // 将数组容器转换为字符串
            let allGoodsSn = selectedArray.join(',');
            if (allGoodsSn == "") {
                this.app.toastWarning('所选商品为空！');
                return;
            }
            this._masterService
                .postData(this.update, { snList: allGoodsSn, categoryId: this.selectCategoryId })
                .subscribe((res) => {
                    if (res.statusCode == 200) {
                        this.app.toastSuccess('修改成功！');
                        this.isCheckAll = false;
                        this.cancle();
                        this.onChangeTable();
                    } else if (res.statusCode == 401) {
                        this.app.logOff();
                    } else {
                        this.app.toastError('错误信息： ' + res.errorMessage);
                    }
                })
        }
    }
    // 取消
    cancle() {
        $('#editGoodsInvoiceBox').addClass('modalBoxHide');
        $('#editGoodsInvoiceContainer').addClass('modalBoxHide');
        this.selectCategoryName = "";
        this.selectCategoryId = 0;
        this.selectedGoodsSn = '';
        this.getSearchCategoryList(this.selectCategoryName);
    }

    // 搜索的时候获取所有开票分类
    getSearchCategoryList(categoryName) {
        let urlObject = {
            name: categoryName
        }
        this._masterService
            .getData(this.searchList, urlObject)
            .subscribe((res) => {
                if (res.statusCode == 200) {
                    this.invoiceSearchListEdit = res.data;
                    this.cdRef.detectChanges();
                } else if (res.statusCode == 401) {
                    this.app.logOff();
                } else {
                    this.app.toastError('错误信息：' + res.errorMessage);
                }
            })
    }
    // 搜索列表中已经选中的商品
    addSelectItem(name, id) {
        this.selectCategoryName = name;
        this.selectCategoryId = id;
        this.getSearchCategoryList(name);
    }

    // 全选
    public isCheckAll = false;
    checkAll() {
        if (!this.isCheckAll) {
            this.isCheckAll = true;
            for (let i = 0; i < this.rows.length; i++) {
                this.rows[i].isChecked = true;
            }
            return;
        }
        for (let i = 0; i < this.rows.length; i++) {
            this.rows[i].isChecked = false;
        }
        this.isCheckAll = false;
    }

    // 批量导入
    public batchItem = {
        excelUrl: ''
    };

    showBatchModel() {
        $('#uploadMask').removeClass('modalBoxHide');
        $('#upload').removeClass('modalBoxHide');
    }

    // 上传excel对象
    public excelUploader: FileUploader = new FileUploader({
        url: this.addFileItem,
        method: 'post',
        itemAlias: 'uploadedFile'
    })

    // 上传
    uploadFile() {
        this.btnEnabled = 0;
        let that = this;
        let thisItem = that.excelUploader.queue[that.excelUploader.queue.length - 1];
        if (thisItem == undefined) {
            this.app.toastWarning("请选择excel文件！");
            return;
        }

        // 上传文件后缀并验证
        let suffix = thisItem.some.name.substr(thisItem.some.name.lastIndexOf('.') + 1)
        if (suffix != 'xlsx') {
            this.app.toastWarning('请上传excel格式文件');
            return;
        }

        thisItem.withCredentials = false;
        // 成功回调
        thisItem.onSuccess = function (response, status, headers) {
            // 上传文件成功
            if (status == 200) {
                // 上传文件后获取服务器返回的数据
                let tempRes = JSON.parse(response);
                that.batchItem.excelUrl = tempRes.data.url[0];
                that.excelUploader.queue = [];
                that.app.toastSuccess('上传成功！');
                that.btnEnabled = 1;
            } else {
                // 上传文件后获取服务器返回的数据错误
                that.app.toastError('上传失败!');
                that.btnEnabled = 1;
            }
        };

        thisItem.onError = function (response, status, headers) {
            // 错误回调
            that.app.toastError('发生了错误！')
            that.btnEnabled = 1;
        };

        thisItem.upload(); // 开始上传
    }

    // 新建保存
    public saveUpload() {
        if (this.batchItem.excelUrl == '') {
            this.app.toastWarning('请上传用户模板！');
            return;
        }
        // 插入
        this._masterService.postData(this.batchAddItem, this.batchItem)
            .subscribe((res) => {
                if (res.statusCode == 200) {
                    this.app.toastSuccess('导入成功！');
                    this.cancelUpload();
                    this.onChangeTable();
                } else {
                    this.app.toastError('错误信息: ' + res.errorMessage);
                }
            })
    }
    // 取消上传
    cancelUpload() {
        this.batchItem.excelUrl = '';
        this.excelUploader.queue = [];
        $('#uploadMask').addClass('modalBoxHide');
        $('#upload').addClass('modalBoxHide');
    }
}

